﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Sita.Data.Context;
using Sita.Entities;
using Sita.Data.Core;

namespace Sita.Data.Repositories
{
    public class WorkOrderRepository : GenericRepository<WorkOrder>
    {
        public WorkOrderRepository() :
            base(new SitaContext())
        { }

        public IList<WorkOrder> GetPaginatedByBusinessUnitID(int businessUnitID, int pageIndex, int pageSize, string sortColumn, bool ascending, out int totalRows)
        {
            RepositoryHelper<WorkOrder> Helper = new RepositoryHelper<WorkOrder>();
            var OrderByExpr = Helper.GetOrderExpression(sortColumn);

            IQueryable<WorkOrder> ReturnSet;

            ReturnSet = (base.StoreContext as ISitaContext).WorkOrders
                .Where(wo => wo.BusinessUnitID == businessUnitID)
                .Select(wo => wo);

            totalRows = ReturnSet.Count();

            return (ascending)
                                ?
                                    ((IOrderedQueryable<WorkOrder>)System.Linq.Queryable.OrderBy(ReturnSet, OrderByExpr))
                                        .Skip(pageIndex * pageSize)
                                        .Take(pageSize)
                                        .Include("WorkOrderStatu")
                                        .Include("Vehicle")
                                        .Include("Vehicle.Customer")
                                        .ToList()
                                :
                                    ((IOrderedQueryable<WorkOrder>)System.Linq.Queryable.OrderByDescending(ReturnSet, OrderByExpr))
                                        .Skip(pageIndex * pageSize)
                                        .Take(pageSize)
                                        .Include("WorkOrderStatu")
                                        .Include("Vehicle")
                                        .Include("Vehicle.Customer")
                                        .ToList();

        }

        public WorkOrder GetFullWO(int woid)
        {
            WorkOrder WO;
            WO = (base.StoreContext as ISitaContext).WorkOrders
                .Where(wo => wo.WorkOrderID == woid)
                .Include("BusinessUnit")
                .Include("Vehicle")
                .Include("Vehicle.VehicleType")
                .Include("Vehicle.VehicleBrand")
                .Include("Vehicle.Customer")
                .Include("WorkOrderEmployees")
                .Include("WorkOrderEmployees.Employee")
                .Include("WorkOrderReplacements")
                .Include("WorkOrderReplacements.Replacement")
                .SingleOrDefault();
            return WO;
        }
    }
}
